<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="流程ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入流程ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程名称" prop="processName">
        <el-input
          v-model="queryParams.processName"
          placeholder="请输入流程名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['flow:process:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['flow:process:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['flow:process:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['flow:process:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="processList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="流程ID" align="center" prop="id" />
      <el-table-column label="流程名称" align="center" prop="processName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['flow:process:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['flow:process:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改流程对话框 -->
    <el-dialog :title="isAdd ? '新增流程' : '修改流程'" v-model="open" width="1600px" append-to-body fullscreen destroy-on-close>
      <el-container style="padding: 0 0;">
        <!-- header -->
        <el-header 
          height="75px" 
          style="
            width: 100%;
            background-color: #eef1f6; 
            border-bottom: 1px solid #ccc; 
            display: flex; 
            align-items: center;
            justify-content: center;
            "
        >
          <el-form ref="processRef" :model="form" :rules="rules" label-width="80px" style="width: 100%;">
            <el-row :gutter="15">
              <el-col :span="8">
                <el-form-item label="流程名称" prop="processName">
                  <el-input v-model="form.processName" placeholder="请输入流程名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-header>
        <!-- body -->
        <el-container>
          <!-- 左 -->
          <el-aside width="250px" class="left" style="margin: 0 0;">
            <LeftSidebar />
          </el-aside>
          <!-- 中 -->
          <el-main style="padding: 5px 5px;">
            <!-- 套一层div, 并绑定`drop`事件 -->
            <div class="dnd-flow" @drop="onDrop">
              <VueFlow
                :style="{ background: '#f5f5f5' }"
                v-model:nodes="nodes"
                v-model:edges="edges"
                :default-zoom="1.5"
                :min-zoom="0.2"
                :max-zoom="4"
                @dragover="onDragOver" 
                @dragleave="onDragLeave"
              >
                <!-- 背景 -->
                <DropzoneBackground
                  :style="{
                    backgroundColor: isDragOver ? '#e7f3ff' : 'transparent',
                    transition: 'background-color 0.2s ease',
                  }"
                >
                  <p v-if="isDragOver" style="font-size: 25px; font-weight: 600;">
                    松手放置节点
                  </p>
                </DropzoneBackground>

                <!-- 小地图 -->
                <MiniMap />
                <!-- 控制栏 -->
                <Controls />

                <template #node-custom-input="nodeProps">
                  <CustomStart v-bind="nodeProps" />
                </template>
                <template #node-custom-output="nodeProps">
                  <CustomStop v-bind="nodeProps" />
                </template>
                <template #node-custom1="nodeProps">
                  <CustomNode1 v-bind="nodeProps" />
                </template>
                <template #node-custom2="nodeProps">
                  <CustomNode2 v-bind="nodeProps" />
                </template>
              </VueFlow>
            </div>
          </el-main>
          <!-- 右 -->
          <el-aside width="250px" class="right" style="margin: 0 0;">
            <RightSidebar v-model="selectedObj"/>
          </el-aside>
        </el-container>
      </el-container>
    </el-dialog>
  </div>
</template>

<script setup name="Process">
import { ref, reactive } from 'vue'
import { listProcess, getProcess, delProcess, updateProcess, addProcess } from "@/api/flow/process"

const { proxy } = getCurrentInstance()

import { Controls } from '@vue-flow/controls'
import { MiniMap } from '@vue-flow/minimap'
import { VueFlow, useVueFlow } from '@vue-flow/core'

import CustomStart from '@/views/flow/add/CustomStart.vue'
import CustomStop from '@/views/flow/add/CustomStop.vue'
import CustomNode1 from '@/views/flow/add/CustomNode1.vue'
import CustomNode2 from '@/views/flow/add/CustomNode2.vue'
import LeftSidebar from '@/views/flow/add/LeftSidebar.vue'
import DropzoneBackground from '@/views/flow/add/DropzoneBackground.vue'
import RightSidebar from '@/views/flow/add/RightSidebar.vue'
import TopHeader from '@/views/flow/add/TopHeader.vue'

import useDragAndDrop from '@/views/flow/add/useDnD.js'
const { onDragOver, onDrop, onDragLeave, isDragOver } = useDragAndDrop()
const { onConnect, addEdges, onNodeClick, onEdgeClick, fitView } = useVueFlow()

const processList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const daterangeCreateTime = ref([])

const data = reactive({
  // 流程名称备注表单
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    processName: null,
    remark: null,
    createTime: null
  },
  rules: {
    processName: [
      { required: true, message: "流程名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// ================================
// 节点和连接
const nodes = ref([])
const edges = ref([])
// 当前选中的node或edge
const selectedObj = ref({})
// 当前是在修改还是新增
const isAdd = ref(false)
// ================================

/** 查询流程列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0]
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1]
  }
  listProcess(queryParams.value).then(response => {
    processList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    processName: null,
    remark: null,
    createTime: null
  }
  proxy.resetForm("processRef")
  nodes.value = []
  edges.value = []
  selectedObj.value = {}
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增流程 */
function handleAdd() {
  reset()
  isAdd.value = true
  open.value = true
  nodes.value = [
    {
      id: "start",
      type: "custom-input",
      label: "开始",
      position: {
        x: 85,
        y: 160
      },
      description: "开始",
      data: { description: "开始" }
    },
    {
      id: "end",
      type: "custom-output",
      label: "结束",
      position: {
        x: 650,
        y: 160
      },
      description: "结束",
      data: { description: "结束" }
    },
    {
      id: "AVG",
      type: "custom1",
      label: "AVG",
      position: {
        x: 200,
        y: 150
      },
      description: "AVG",
      data: { description: "AVG" }
    },
    {
      id: "色谱",
      type: "custom1",
      label: "色谱",
      position: {
        x: 350,
        y: 150
      },
      description: "色谱",
      data: { description: "色谱" }
    },
    {
      id: "机械臂",
      type: "custom2",
      label: "机械臂",
      position: {
        x: 500,
        y: 150
      },
      description: "机械臂",
      data: { description: "机械臂" }
    }
  ]
  edges.value = [
    {
      id: "e: AVG->色谱",
      source: "AVG",
      target: "色谱",
      type: "step",
      label: "操作名称",
      animated: true,
      labelBgStyle: { fill: '#fff' },
      labelBgPadding: [8, 3],
      labelBgBorderRadius: 5,
      data: { description: '' }
    },
    {
      id: "e: start->AVG",
      source: "start",
      target: "AVG",
      type: "step",
      label: "操作名称",
      animated: true,
      labelBgStyle: { fill: '#fff' },
      labelBgPadding: [8, 3],
      labelBgBorderRadius: 5,
      data: { description: '' }
    },
    {
      id: "e: 机械臂->end",
      source: "机械臂",
      target: "end",
      type: "step",
      label: "操作名称",
      animated: true,
      labelBgStyle: { fill: '#fff' },
      labelBgPadding: [8, 3],
      labelBgBorderRadius: 5,
      data: { description: '' }
    },
    {
      id: "e: 色谱->机械臂",
      source: "色谱",
      target: "机械臂",
      type: "step",
      label: "操作名称",
      animated: true,
      labelBgStyle: { fill: '#fff' },
      labelBgPadding: [8, 3],
      labelBgBorderRadius: 5,
      data: { description: '' }
    }
  ]
  setTimeout(() => {
    fitView()
  }, 100)
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  isAdd.value = false
  const _id = row.id || ids.value
  getProcess(_id).then(response => {
    open.value = true
    form.value = response.data.flowProcess
    nodes.value = response.data.flowNodeList
    nodes.value.forEach(n => {
      n['position'] = {}
      n.position['x'] = n.x
      n.position['y'] = n.y
      n['data'] = {}
      n.data['description'] = n.description
    })
    edges.value = response.data.flowEdgeList
    edges.value.forEach(e => {
      e['animated'] = true
      e['labelBgStyle'] = { fill: '#fff' }
      e['labelBgPadding'] = [8, 3]
      e['labelBgBorderRadius'] = 5
      e['data'] = {}
      e.data['description'] = e.description
    })
    // 流程图居中
    setTimeout(() => {
      fitView()
    }, 100)
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["processRef"].validate(valid => {
    if (valid) {
      nodes.value.forEach(n => {
        n['x'] = n.position.x
        n['y'] = n.position.y
        n['description'] = n.data.description
      })
      edges.value.forEach(e => {
        e['description'] = e.data.description
      })
      const data = {
        flowProcess: form.value,
        flowNodeList: nodes.value,
        flowEdgeList: edges.value
      }
      if (isAdd.value) {
        // 新增
        addProcess(data).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      } else {
        // 修改
        updateProcess(data).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      }
       
    }
  })
}

// 节点连接时的回调函数
onConnect(params => {
  const { source, target } = params;
  addEdges([{
    id: `e: ${source}->${target}`,
    source,
    target,
    type: 'step',
    label: '操作名称',
    animated: true,
    labelBgStyle: { fill: '#fff' },
    labelBgPadding: [8, 3],
    labelBgBorderRadius: 5
  }])
})
// 点击节点时的回调函数
onNodeClick(e => {
  selectedObj.value = e.node
})
// 点击连接时的回调函数
onEdgeClick(e => {
  selectedObj.value = e.edge
})

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除流程编号为"' + _ids + '"的数据项？').then(function() {
    return delProcess(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('flow/process/export', {
    ...queryParams.value
  }, `process_${new Date().getTime()}.xlsx`)
}

getList()
</script>
